package com.hanxiaozhang.jdk8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BinaryOperator;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/12/28
 * @since 1.0.0
 */
public class No11BinaryOperator {

    public static void main(String[] args) {

        /*
        BinaryOperator接口继承BiFunction接口,它接受两个相同类型的操作数并对其进行处理，
        然后返回与操作数相同类型的结果。
        <T> BinaryOperator<T> minBy(Comparator<? super T> comparator);
        <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator);
         */

        Student student1 = new Student("小张", 20);
        Student student2 = new Student("小王", 23);
        Student student3 = new Student("小周", 24);
        Student student4 = new Student("小韩", 21);
        List<Student> list = Arrays.asList(student1, student2, student3, student4);

        // maxBy()
        BinaryOperator<Student> maxBinaryOperator = BinaryOperator.maxBy(Comparator.comparing(Student::getAge));
        Student max = null;
        for (Student t : list) {
            if (max == null) {
                max = t;
            } else {
                max = maxBinaryOperator.apply(max, t);
            }
        }
        System.out.println("年龄最大的学生：" + max);
        System.out.println("---- ---- ---- ----");

        // minBy()
        BinaryOperator<Student> minBinaryOperator = BinaryOperator.minBy(Comparator.comparing(Student::getAge));
        Student min = null;
        for (Student t : list) {
            if (min == null) {
                min = t;
            } else {
                min = minBinaryOperator.apply(min, t);
            }
        }
        System.out.println("年龄最小的学生：" + min);

    }


    public static class Student {

        private String name;

        private Integer age;


        public Student(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
